<?php


namespace Admin\Controller;

use Think\Controller;

class RoleController extends AdminController
{
    public function showList()
    {
        $roles = D('role')->select();
        $this->assign('roles', $roles);
        $this->display();
    }

    //    添加角色
    public function add()
    {
        if (empty($_POST)) {
            $this->display();
        } else {
            $role = D('role');
            //create（） 验证角色是否存在
            $info = $role->create();
            if ($info) {
                $role->add($info);
                $this->success('角色添加成功', 'showlist');
            } else {
                $this->error($role->getError());
            }
        }
    }
    //    修改角色
    public function edit($role_id)
    {
        $role = D('role');
        if (empty($_POST)) {
            $item = $role->find($role_id);
            $this->assign('role', $item);
            $this->display();
        } else {
//            dump($_POST);
            $res = $role->save($_POST);
//            dump($res);
            if ($res) {
                $this->redirect('showList', array(), 2, '修改角色成功');
            } else {
                $this->redirect('edit', array('role_id' => $_POST['role_id']), 2, '修改角色失败');
            }
        }
    }
    public function del($role_id)
    {
        $res = D('role')->delete($role_id);
        if ($res !== false) {
            $this->redirect('showList', array(), 2, '删除角色成功');
        } else {
            $this->redirect('del', array(), 2, '删除角色失败');
        }
    }
    //分配权限
    public function allocate($role_id){
        if(empty($_POST)){
            $role=D('role')->find($role_id);
            $auth_a=D('auth')->where('auth_level=0')->select();
            $auth_b=D('auth')->where('auth_level>0')->select();
            $this->assign([
               'role'=>$role,
                'auth_a'=>$auth_a,
                'auth_b'=>$auth_b,
            ]);
            $this->display();
        }else{
            $role_auth_ids=implode(',',$_POST['auth_id']);
            $auth_info=D('auth')->select($role_auth_ids);
            $auth_ac='';
            foreach ($auth_info as $v){
                if(!empty($v['auth_c'])&&!empty($v['auth_a'])){
                    $auth_ac.=$v['auth_c'].'-'.$v['auth_a'].',';
                }
            }
            $s=rtrim($auth_ac,',');
            $res=D('role')->where("role_id=$role_id")->save([
               'role_auth_ids'=>$role_auth_ids,
               'role_auth_ac'=>$s
            ]);
            if($res){
                $this->success('权限分配成功','showList');
            }else{
                $this->error('权限分配失败');
            }

        }
    }

}